from flask import request, jsonify, Blueprint
import json

from exts import db
from models import Opera
from models import Character
from models import OperaPlot
from config import static_prefix

bp = Blueprint('opera', __name__, url_prefix='/opera')


@bp.route('/all', methods=['GET'])
def opera_list():
    # 返回所有歌剧的图片路径、歌剧名、作家名
    opr_list = Opera.query.all()
    ret_list = []
    for opr in opr_list:
        ret_list.append({
            'cps_name': opr.cps_name,
            'opr_name': opr.opr_name,
            'opr_name_e': opr.opr_name_e,
            'lang': opr.lang,
            'pic_src': static_prefix + 'picture?type=opera&filename=' + opr.pic_src,
            'like_cnt': opr.like_cnt,
            'simple_intro': opr.simple_intro
        })
    return jsonify(ret_list)


@bp.route('/like', methods=['POST'])
def opera_like():
    # 给歌剧点赞
    data = request.get_json()
    res = {'msg': '操作成功'}
    if 'opr_name' not in data:
        res['msg'] = '请求参数出错'
        return jsonify(res)
    name = data['opr_name']
    opr = Opera.query.filter_by(opr_name=name).all()
    if len(opr) == 0:
        res['msg'] = '请求的歌剧不存在'
        return jsonify(res)
    Opera.query.filter_by(opr_name=name).update({'like_cnt': opr[0].like_cnt + 1})
    db.session.commit()
    return jsonify(res)


@bp.route('/detail', methods=['POST'])
def opera_detail():
    # 返回所有歌剧的图片路径、歌剧名、作家名
    data = request.get_json()
    res = {'msg': '操作成功'}
    if 'opr_name' not in data:
        res['msg'] = '请求参数出错'
        return jsonify(res)
    opr = Opera.query.filter_by(opr_name=data['opr_name']).all()
    if len(opr) == 0:
        res['msg'] = '请求的歌剧不存在'
        return jsonify(res)
    opr = opr[0]
    res['cps_name'] = opr.cps_name
    res['opr_name'] = opr.opr_name
    res['opr_name_e'] = opr.opr_name_e
    res['lang'] = opr.lang
    res['pic_src'] = static_prefix + 'picture?type=opera&filename=' + opr.pic_src
    res['like_cnt'] = opr.like_cnt
    res['simple_intro'] = opr.simple_intro
    res['intro'] = opr.intro
    res['chapter_list'] = []
    res['plot_list'] = []
    # 构造chapter_list（实际上是character，写错了）
    characters = Character.query.filter_by(opr_name=data['opr_name']).all()
    for i in characters:
        res['chapter_list'].append({
            'chapter_name': i.character_name,
            'chapter_simple_intro': i.intro,
            'chapter_pic_src': static_prefix + 'picture?type=character&filename=' + i.pic_src
        })
    # 构造plot_list
    plots = OperaPlot.query.filter_by(opr_name=data['opr_name']).all()
    for i in plots:
        res['plot_list'].append({
            'name': i.name,
            'plot': json.loads(i.plot)
        })
    print(res)
    return jsonify(res)
